package com.ruoyi.project.zxbd.controller;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/bd/function/task")
public class TaskController extends BaseController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    FormService formService;
    @Autowired
    private HistoryService historyService;

    /**
     * 查询待办任务列表
     * @return
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:list')")
    @GetMapping("/mylist")
    public TableDataInfo mylist(){
        PageData pd = this.getPageData();
        startPage();
        LoginUser loginUser = getLoginUser();
        String username = loginUser.getUsername();
        TaskQuery condition = taskService.createTaskQuery().taskAssignee(username);//condition中只有assignee和mysql字段有值
        String task_name = (String) pd.get("task_name");
        if (StringUtils.isNotEmpty(task_name)){
            condition.taskName(task_name);
        }
        String process_name = (String) pd.get("process_name");
        if (StringUtils.isNotEmpty(process_name)) {
            condition.processDefinitionName(process_name);
        }
        int pageNum=1;
        int pageSize=10;
        if(pd.get("pageNum")!=null){
            pageNum=Integer.parseInt((String)pd.get("pageNum"));
        }
        if(pd.get("pageSize")!=null){
            pageSize=Integer.parseInt((String)pd.get("pageSize"));
        }
        int start = (pageNum-1) * pageSize;
        // 过滤掉流程挂起的待办任务(查询符合条件的未完成的任务数量)
        int total = condition.active().orderByTaskCreateTime().desc().list().size();
        List<Task> taskList = condition.active().orderByTaskCreateTime().desc().listPage(start,pageSize);

        List<PageData> tasks = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        taskList.stream().forEach(a->{
            ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(a.getProcessInstanceId()).singleResult();
            PageData info = new PageData();
            info.put("task_name",a.getName());
            info.put("process_instance_id",a.getProcessInstanceId());
            info.put("execution_id",a.getExecutionId());
            info.put("business_key",process.getBusinessKey());
            info.put("process_name",process.getProcessDefinitionName());
            info.put("starter",process.getStartUserId());
            info.put("assignee",a.getAssignee());
            info.put("create_time",sdf.format(a.getCreateTime()));
            info.put("start_time",sdf.format(process.getStartTime()));

            info.put("task_id",a.getId());
            String formKey = formService.getTaskFormData(a.getId()).getFormKey();
            info.put("form_key",formKey);
            tasks.add(info);
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(tasks);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 办理一个用户任务
     * 使用pd这个对象来接收前端传递过来的参数：任务id、审批结果、审批意见、人事
     */
    @PreAuthorize("@ss.hasPermi('bd:partner:add')")
    @PostMapping("/completeTask")
    public AjaxResult completeTask(@RequestBody PageData pd){
        LoginUser loginUser = getLoginUser();
        String username = loginUser.getUsername();
        String taskId = (String)pd.get("task_id");
        taskService.setAssignee(taskId,username);
        //查找出流程实例id
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        if(pd==null){
            taskService.complete(taskId);
        }else{
            //添加审批意见
            if(pd.get("suggestion")!=null){
                taskService.addComment(taskId,processInstanceId,(String) pd.get("suggestion"));
                pd.remove("suggestion");
            }
            taskService.complete(taskId,pd);
        }
        return AjaxResult.success();
    }
}
